import { http } from '@/utils/request'
import request from '@/utils/request'
import type { ApiResponse } from '@/types'

// 从 Cookie 中获取 token 的辅助函数
const getTokenFromCookie = (): string | null => {
  const cookies = document.cookie.split(';')
  for (const cookie of cookies) {
    const [name, value] = cookie.trim().split('=')
    if (name === 'token') {
      return value
    }
  }
  return null
}

// Dify AI 聊天请求参数
export interface DifyChatRequest {
  message: string
  conversation_id?: string
  inputs?: Record<string, any>
  response_mode?: 'streaming' | 'blocking'
}

// Dify AI 聊天响应块
export interface DifyChatChunk {
  type: 'start' | 'chunk' | 'end' | 'error'
  message?: string
  conversation_id?: string
}

// 语音转文字请求参数
export interface VoiceToTextRequest {
  file: File
}

// 语音转文字响应
export interface VoiceToTextResponse {
  text: string
}

// 文字转语音请求参数
export interface TextToVoiceRequest {
  text?: string
  message_id?: string
}

// 快捷操作
export interface QuickAction {
  id: string
  title: string
  description: string
  icon: string
  action: string
  color: string
}

// 聊天历史消息
export interface ChatMessage {
  id: string
  conversationId: string
  messageType: 'USER' | 'ASSISTANT'
  content: string
  messageFormat: 'TEXT' | 'AUDIO' | 'IMAGE'
  createdAt: string
}

// 聊天历史响应
export interface ChatHistoryResponse {
  items: ChatMessage[]
  pagination: {
    total: number
    page: number
    pageSize: number
    totalPages: number
  }
}

// 应用信息
export interface AppInfo {
  app_id: string
  app_name: string
  app_description: string
  app_type: string
  app_version: string
  app_icon: string
  app_icon_background: string
  app_icon_mode: string
  app_icon_round: boolean
  app_icon_theme: string
  app_icon_theme_color: string
  app_icon_theme_color_light: string
  app_icon_theme_color_dark: string
  app_icon_theme_color_auto: boolean
  app_icon_theme_color_auto_light: string
  app_icon_theme_color_auto_dark: string
  app_icon_theme_color_auto_primary: string
  app_icon_theme_color_auto_secondary: string
  app_icon_theme_color_auto_accent: string
  app_icon_theme_color_auto_neutral: string
  app_icon_theme_color_auto_surface: string
  app_icon_theme_color_auto_background: string
  app_icon_theme_color_auto_error: string
  app_icon_theme_color_auto_warning: string
  app_icon_theme_color_auto_info: string
  app_icon_theme_color_auto_success: string
  app_icon_theme_color_auto_primary_light: string
  app_icon_theme_color_auto_primary_dark: string
  app_icon_theme_color_auto_secondary_light: string
  app_icon_theme_color_auto_secondary_dark: string
  app_icon_theme_color_auto_accent_light: string
  app_icon_theme_color_auto_accent_dark: string
  app_icon_theme_color_auto_neutral_light: string
  app_icon_theme_color_auto_neutral_dark: string
  app_icon_theme_color_auto_surface_light: string
  app_icon_theme_color_auto_surface_dark: string
  app_icon_theme_color_auto_background_light: string
  app_icon_theme_color_auto_background_dark: string
  app_icon_theme_color_auto_error_light: string
  app_icon_theme_color_auto_error_dark: string
  app_icon_theme_color_auto_warning_light: string
  app_icon_theme_color_auto_warning_dark: string
  app_icon_theme_color_auto_info_light: string
  app_icon_theme_color_auto_info_dark: string
  app_icon_theme_color_auto_success_light: string
  app_icon_theme_color_auto_success_dark: string
}

// 应用参数
export interface AppParameters {
  parameters: Record<string, any>
}

// 停止响应请求参数
export interface StopResponseRequest {
  task_id: string
}

// Dify Workflow 聊天请求参数
export interface DifyWorkflowChatRequest {
  message: string
  conversation_id?: string
  inputs?: Record<string, any>
  response_mode?: 'blocking'
  files?: File[] // 添加文件上传支持
}

// Dify Workflow 聊天响应
export interface DifyWorkflowChatResponse {
  workflow_run_id: string
  task_id: string
  data: {
    id: string
    workflow_id: string
    status: string
    outputs?: any
    error?: string
    elapsed_time?: number
    total_tokens?: number
    total_steps?: number
    created_at?: number
    finished_at?: number
  }
}

/**
 * Dify AI 聊天 - 流式响应
 * @param data 聊天请求参数
 * @param onChunk 处理响应块的回调
 * @param onComplete 处理完整响应的回调
 * @param onError 处理错误的回调
 * @returns 取消函数
 */
export const sendMessageStream = (
  data: DifyChatRequest,
  onChunk: (chunk: DifyChatChunk) => void,
  onComplete: (fullResponse: string) => void,
  onError: (error: string) => void
): (() => void) => {
  const controller = new AbortController()
  
  const fetchData = async () => {
    try {
                   console.log('开始发送请求到:', '/api/client/dify-ai/chat')
      const response = await fetch('/api/client/dify-ai/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${getTokenFromCookie()}`
        },
        body: JSON.stringify(data),
        signal: controller.signal
      })

      console.log('收到响应:', response.status, response.statusText)
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const reader = response.body?.getReader()
      if (!reader) {
        throw new Error('No response body')
      }

      const decoder = new TextDecoder()
      let buffer = ''

      while (true) {
        const { done, value } = await reader.read()
        
        if (done) break
        
        buffer += decoder.decode(value, { stream: true })
        console.log('当前缓冲区:', buffer)
        
        // 查找完整的 data: 行
        const dataLines = buffer.match(/data: .*\n/g)
        if (dataLines) {
          // 处理完整的行
          for (const line of dataLines) {
            const cleanLine = line.trim()
            console.log('处理完整行:', cleanLine)
            
            if (cleanLine.startsWith('data: ')) {
              try {
                const jsonStr = cleanLine.slice(6)
                const chunk = JSON.parse(jsonStr)
                console.log('解析的chunk:', chunk)
                onChunk(chunk)
                
                if (chunk.type === 'end') {
                  console.log('收到结束信号')
                  onComplete(chunk.message || '')
                  return
                } else if (chunk.type === 'error') {
                  console.log('收到错误信号')
                  onError(chunk.message || '未知错误')
                  return
                }
                             } catch (e) {
                 console.error('解析响应块失败:', e, '原始数据:', cleanLine.slice(6))
               }
            }
          }
          
          // 移除已处理的行，保留未完成的行
          const lastNewlineIndex = buffer.lastIndexOf('\n')
          if (lastNewlineIndex !== -1) {
            buffer = buffer.slice(lastNewlineIndex + 1)
          }
        }
      }
    } catch (error: any) {
      if (error.name === 'AbortError') {
        return
      }
      onError(error.message || '网络错误')
    }
  }

  fetchData()
  
  return () => controller.abort()
}

/**
 * 语音转文字
 */
export const voiceToText = (data: VoiceToTextRequest): Promise<ApiResponse<VoiceToTextResponse>> => {
  const formData = new FormData()
  formData.append('file', data.file)
  
  return http.post('/client/dify-ai/voice-to-text', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 文字转语音
 */
export const textToVoice = (data: TextToVoiceRequest): Promise<Blob> => {
  return request.post('/client/dify-ai/text-to-audio', data, {
    responseType: 'blob'
  })
}

/**
 * 获取聊天历史
 */
export const getChatHistory = (params: { page?: number; pageSize?: number } = {}): Promise<ApiResponse<ChatHistoryResponse>> => {
  return http.get('/client/dify-ai/chat-history', { params })
}

/**
 * 获取应用信息
 */
export const getAppInfo = (): Promise<ApiResponse<AppInfo>> => {
  return http.get('/client/dify-ai/app-info')
}

/**
 * 获取应用参数
 */
export const getAppParameters = (): Promise<ApiResponse<AppParameters>> => {
  return http.get('/client/dify-ai/app-parameters')
}

/**
 * 获取快捷操作
 */
export const getQuickActions = (): Promise<ApiResponse<QuickAction[]>> => {
  return http.get('/client/dify-ai/quick-actions')
}

/**
 * 停止响应
 */
export const stopResponse = (data: StopResponseRequest): Promise<ApiResponse<{ task_id: string }>> => {
  return http.post('/client/dify-ai/stop-response', data)
}

/**
 * Dify Workflow 聊天 - Blocking 模式
 * @param data 聊天请求参数
 * @returns Promise<ApiResponse<DifyWorkflowChatResponse>>
 */
export const sendWorkflowMessage = (data: DifyWorkflowChatRequest): Promise<ApiResponse<DifyWorkflowChatResponse>> => {
  // 如果有文件，使用 FormData
  if (data.files && data.files.length > 0) {
    const formData = new FormData()
    formData.append('message', data.message)
    
    if (data.conversation_id) {
      formData.append('conversation_id', data.conversation_id)
    }
    
    if (data.inputs) {
      formData.append('inputs', JSON.stringify(data.inputs))
    }
    
    if (data.response_mode) {
      formData.append('response_mode', data.response_mode)
    }
    
    // 添加文件
    data.files.forEach((file, index) => {
      formData.append('files', file)
    })
    
    return http.post('/client/dify-ai/workflow-chat', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
  
  // 没有文件时使用 JSON
  return http.post('/client/dify-ai/workflow-chat', data)
}

// 建议问题响应
export interface SuggestedQuestionsResponse {
  suggested_questions: string[]
  message_id: string
}

/**
 * 获取下一轮建议问题列表
 * @param messageId 消息ID
 * @returns Promise<ApiResponse<SuggestedQuestionsResponse>>
 */
export const getSuggestedQuestions = (messageId: string): Promise<ApiResponse<SuggestedQuestionsResponse>> => {
  return http.get(`/client/dify-ai/messages/${messageId}/suggested`)
}
